package com.jiantong.web.open.app.work;

import com.jiantong.user.service.BreedFactoryReadService;
import com.jiantong.web.core.enums.ExceptionCode;
import com.jiantong.work.model.PollutionControl;
import com.jiantong.work.service.PollutionControlReadService;
import com.jiantong.work.service.PollutionControlWriteService;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.annotations.OpenBean;
import io.terminus.pampas.openplatform.annotations.OpenMethod;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Strings;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;
import java.util.Map;

/**
 *
 */
@Slf4j
@OpenBean
public class PollutionControlApis {
    @RpcConsumer
    private PollutionControlReadService pollutionControlReadService;
    @RpcConsumer
    private PollutionControlWriteService pollutionControlWriteService;
    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;

    /**
     * 养殖场根据id
     * 查询所有数据
     */
    @OpenMethod(
            key = "find.pollution.control.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public PollutionControl findById(Long id) {
        if(id == null){
            log.error("id should be not null");
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),"" +
                    "id should be not null");
        }
        Response<PollutionControl> resp = pollutionControlReadService.findById(id);
        if (!resp.isSuccess()) {
            log.error("failed to find pollution control by id = {}, cause : {}", id, resp.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),
                    resp.getError());
        }
        return resp.getResult();
    }

    /**
     * 养殖场状态查询
     *
     * @return status不唯一
     */
    @OpenMethod(
            key = "paging.pollution.control",
            paramNames = {"pageNo", "pageSize", "status","breedFactoryId"},
            httpMethods = RequestMethod.GET)
    public Paging<PollutionControl> pagingPollutionControl(Integer pageNo, Integer pageSize,
                                                           Integer status, Long breedFactoryId) {
        if(breedFactoryId == null){
            log.error("breedFactoryId should be not null");
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),
                    "breedFactoryId should be not null");
        }
        Response<Paging<PollutionControl>> resp = pollutionControlReadService.pagingPollutionControl(pageNo, pageSize, status,breedFactoryId);
        if (!resp.isSuccess()) {
            log.error("failed to paging pollution control{}, cause : {}", resp.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),
                    resp.getError());
        }
        return resp.getResult();
    }

    /**
     * 养殖场合计
     *
     * @return status =1
     */
    @OpenMethod(
            key = "sum.breed.pollution.control",
            paramNames = {"breedFactoryId"},
            httpMethods = RequestMethod.GET)
    public Map aquacultureSum(Long breedFactoryId) {
        if(breedFactoryId == null){
            log.error("breedFactoryId should be not null");
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),
                    "breedFactoryId should be not null");
        }
        Response<Map> resp = pollutionControlReadService.sumDryAndLiquidByBreedFactoryId(breedFactoryId);
        if (!resp.isSuccess()) {
            log.error("failed to paging pollution control{}, cause : {}", resp.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),
                    resp.getError());
        }
        return resp.getResult();
    }

    /**
     * 政府端合计
     * todo key值更改
     * @return status =1
     */
    @OpenMethod(
            key = "paging.governmentSum.control",
            paramNames = { "breedFactoryId","fromDate", "toDate"},
            httpMethods = RequestMethod.GET)
    public Map governmentSum(Long breedFactoryId, String fromDate, String toDate) {
        Date start = null;
        if (!Strings.isNullOrEmpty(fromDate)) {
            start = DateTime.parse(fromDate).toDate();
        }

        Date end = null;
        if (!Strings.isNullOrEmpty(toDate)) {
            end = DateTime.parse(toDate).toDate();
        }
        Response<Map> resp = pollutionControlReadService.sumGovernment(breedFactoryId, start, end);
        if (!resp.isSuccess()) {
            log.error("failed to paging pollution control{}, cause : {}", resp.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),
                    resp.getError());
        }
        return resp.getResult();
    }

    /**
     * 政府端时间查询
     *
     * @return status =1
     */
    @OpenMethod(
            key = "paging.status.pollution.control",
            paramNames = {"pageNo", "pageSize", "breedFactoryId","breedType", "fromDate", "toDate"},
            httpMethods = RequestMethod.GET)
    public Paging<PollutionControl> pagingPollutionControls(Integer pageNo,
                                                            Integer pageSize,
                                                            Long breedFactoryId,
                                                            Integer breedType,
                                                            String fromDate,
                                                            String toDate) {
        Date start = null;
        if (!Strings.isNullOrEmpty(fromDate)) {
            start = DateTime.parse(fromDate).toDate();
        }

        Date end = null;
        if (!Strings.isNullOrEmpty(toDate)) {
            end = DateTime.parse(toDate).toDate();
        }
        Response<Paging<PollutionControl>> resp =
                pollutionControlReadService.pagingPollutionControls(pageNo, pageSize, breedFactoryId,breedType, start, end);
        if (!resp.isSuccess()) {
            log.error("failed to paging pollution control{}, cause : {}", resp.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),
                    resp.getError());
        }
        return resp.getResult();
    }

    @OpenMethod(
            key = "create.pollution.control",
            paramNames = {"pollutionControl","toStatus"},
            httpMethods = RequestMethod.POST)
    public  Map<String , Object> create(PollutionControl pollutionControl,Integer toStatus) {
        Response<Map<String , Object>> response = pollutionControlWriteService.create(pollutionControl,toStatus);
        if (!response.isSuccess()) {
            log.error("failed to create pollution control = {}, cause : {}", pollutionControl,toStatus, response.getError());
            throw new OPServerException(ExceptionCode.DATA_WRITE_FAIL.value(),
                    response.getError());
        }
        return response.getResult();
    }

    @OpenMethod(
            key = "update.pollution.control",
            paramNames = {"pollutionControl","toStatus"},
            httpMethods = RequestMethod.PUT)
    public Map<String , Object> update(PollutionControl pollutionControl,Integer toStatus) {
        if(pollutionControl.getId() == null){
            log.error("id should be not null error = {}, cause : {}", pollutionControl,pollutionControl.getId());
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),
                    "id should be not null");
        }

        Response<Map<String , Object>> statusResponse = pollutionControlReadService.findStatusById(pollutionControl.getId());
        if(statusResponse.isSuccess() && !statusResponse.getResult().get("status").equals(pollutionControl.getStatus())){
            log.error("pollutionControl is already submitted error = {}, cause : {}", pollutionControl.getStatus(),statusResponse.getResult().get("status"));
            throw new OPClientException(ExceptionCode.DOCUMENT_REPEAT_SUBMIT.value(),
                    "this.report.is.already.submitted");
        }
        Response< Map<String , Object>> response = pollutionControlWriteService.update(pollutionControl,toStatus);
        if (!response.isSuccess()) {
            log.error("failed to update pollution control = {}, cause : {}", pollutionControl, response.getError());
            throw new OPServerException(ExceptionCode.DATA_UPDATE_FAIL.value(),
                    response.getError());
        }
        return response.getResult();
    }
}
